package cn.wy.org.service.impl;

import cn.wy.basic.service.BaseService;
import cn.wy.basic.service.impl.BaseServiceImpl;
import cn.wy.basic.util.Md5Utils;
import cn.wy.basic.util.StrUtils;
import cn.wy.org.domain.Employee;

import cn.wy.org.mapper.EmployeeMapper;
import cn.wy.org.service.EmployeeService;
import cn.wy.system.domain.Role;
import cn.wy.system.mapper.RoleMapper;
import cn.wy.user.domain.Logininfo;
import cn.wy.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService{
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public void insert(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);


        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        logininfoMapper.insert(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        super.insert(employee);
        //【角色】为当前员工添加角色信息
        if(employee.getRole_id()!=null){
            employeeMapper.insertRole(employee);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Employee employee = employeeMapper.findOne(id);
        logininfoMapper.delete(employee.getLogininfo_id());
        employeeMapper.deleteEmployeeByEmployeeId(id);
        super.delete(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Employee oldEmployee = employeeMapper.findOne(employee.getId());
        employee.setLogininfo_id(oldEmployee.getLogininfo_id());
        employee.setShop_id(oldEmployee.getShop_id());
        super.update(employee);

        if(employee.getId()!=null){
            //先删除中间表信息
            employeeMapper.deleteEmployeeByEmployeeId(employee.getId());
            //保存修改之后的信息
            employeeMapper.insertRole(employee);
        }

        Logininfo oldLogininfo = logininfoMapper.findOne(oldEmployee.getLogininfo_id());
        BeanUtils.copyProperties(employee, oldLogininfo);
        oldLogininfo.setId(oldEmployee.getLogininfo_id());
        logininfoMapper.update(oldLogininfo);
    }
}
